/**
 * CusContactsAction.java
 * Created at 2017-3-2
 * Created by shihui
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.basic.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.StringUtils;
import com.broadtext.common.utils.UUIDUtils;
import com.broadtext.rms.basic.model.TmEmploy;
import com.broadtext.rms.basic.service.ICusContactsService;
import com.broadtext.rms.basic.service.ITmCustomService;
import com.broadtext.rms.system.service.ISysUserService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>ClassName: CusContactsAction</p>
 * <p>Description: 客户联系人控制层</p>
 * <p>Author: shihui</p>
 * <p>Date: 2017-3-2</p>
 */
@Controller()
@RequestMapping("/main/cusContacts")
public class CusContactsAction {
    
    @Autowired
    @Qualifier("cusContactsServiceImpl")
    private ICusContactsService cusContactsService;
    
    @Autowired
    @Qualifier("tmCustomService")
    private ITmCustomService tmCustomService;
    
    /**
     * 用户Service
     */
    @Autowired
    @Qualifier("sysUserService")
    private ISysUserService sysUserService;
    
    //定义常量
    private static Integer Limit_add_num=1;
    
    /**
     * 日志信息
     */
    public static Logger logger = LoggerFactory.getLogger(TmEmploy.class);
    
    /**
     * 
     * <p>Description: 查询客户联系人列表</p>
     * @param request 请求对象
     * @param response 返回对象
     */
    @SuppressWarnings({ "unchecked" })
    @RequestMapping(value = "/getCusContacts.mvc")
    @ResponseBody
    public void getCusContacts(HttpServletRequest request, HttpServletResponse response) {
        try {
            PageBounds pageBounds;
            pageBounds = new PageBounds();
            Map<String, Object> map;
            String aoData;
            aoData = request.getParameter("aoData");
            JSONArray array;
            array = JSON.parseArray(aoData);
            map = new HashMap<String, Object>();
            if (array != null) {
                Iterator<?> it;
                it = array.iterator();
                while (it.hasNext()) {
                    JSONObject obj;
                    obj = (JSONObject) it.next();
                    if(obj.get("value")!=null && !"".equals(obj.get("value")+"")){
                        map.put(obj.get("name")+"", obj.get("value"));
                    }
                }
            }
          //判断登录账户类型，如果为客户账户则过滤数据，客户类型只看本级和本下级
            Map<String, Object> checkMap;
            List<String> list;
            try {
                checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
                if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                    //该用户是客户账号
                    map.put("cusId", checkMap.get("cusId"));
                    //查询当前登录用户所有下属子节点pk_id
                    list = this.tmCustomService.getChildCusIdArray(checkMap.get("cusId")+"");
                    map.put("ids", list);
                }
            } catch (DaoException e1) {
                e1.printStackTrace();
            }
            pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
            pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit()+Limit_add_num);
            EntityPageBean<Object> pageBean = this.cusContactsService.getCusContacts(map, pageBounds);
            Map<String, Object> dataMap=new HashMap<String, Object>();
            dataMap.put("recordsTotal", pageBean.getiTotalRecords());
            dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
            dataMap.put("aaData", pageBean.getResults());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.write(JSON.toJSONString(dataMap));
            } catch (IOException e) {
                logger.error("查询出错",e);
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        
    }
    
    /**
     * 
     * <p>Description: 删除联系人</p>
     * @param request 请求
     * @param response 响应
     * @return 操作标志
     */
    @RequestMapping(value = "/delete.mvc")
    @ResponseBody
    public Map<String, Object> deleteContacts(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String ids;
        ids = request.getParameter("pkId");
        String[] idArray;
        idArray = ids.split(",");
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try {
            if (!this.cusContactsService.checkUserBind(idArray)) {
                this.cusContactsService.deleteContactsByIds(idArray, sysUser);
                map.put("msg", true);
            } else {
                map.put("msg", "bind");
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 编辑联系人时查看联系人信息</p>
     * @param request 请求
     * @param pkId 联系人ID
     * @return 联系人信息
     */
    @RequestMapping(value = "getContactInfo.mvc")
    @ResponseBody
    public Map<String, Object> getContactInfo(HttpServletRequest request, String pkId) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        try {
            map.put("data", this.cusContactsService.findEntityById(pkId));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 
     * <p>Description: 新增/编辑联系人时查询客户下拉框数据</p>
     * @param request 请求
     * @return 结果
     */
    @RequestMapping(value = "getCustomers.mvc")
    @ResponseBody
    public Map<String, Object> getCustomers (HttpServletRequest request,String parentId) throws ServiceException{
        //Map<String, Object> map;
        
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        List<Object> list;
        //判断当前登录人是否是客户账号，进行数据过滤
        //若新增客户，且当前操作账号为客户类型，新增客户时选择上级客户只能选本级或本下级
        Map<String, Object> checkMap;
        //String operation = "update";
        try {
            checkMap = this.sysUserService.checkUserClass(request.getSession().getAttribute("sys.user").toString());
            if(null != checkMap && "true".equals(checkMap.get("flag").toString())){
                //判断是新增还是编辑操作，新增操作参数为空
               if(StringUtils.isBlank(parentId)){
                   //operation = "save";
                   parentId = checkMap.get("cusId")+"";
               }
            }
        } catch (DaoException e1) {
            e1.printStackTrace();
        }
        list = this.cusContactsService.findCustomerList(parentId);
        map.put("data", list);
        return map;
    }
    
    /**
     * 
     * <p>Description: 查询相应客户下的厂区</p>
     * @param request 请求
     * @return 厂区
     */
    @RequestMapping(value = "getFactory.mvc")
    @ResponseBody
    public Map<String, Object> getFactoryByCustom (HttpServletRequest request) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        String customId;
        customId = request.getParameter("customId");
        try {
            map.put("data", this.cusContactsService.findFactoryByCustomer(customId));
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 
     * <p>Description: 保存或更新客户联系人</p>
     * @param request 请求
     * @param emp 联系人实体
     * @param response 响应
     * @return 结果
     */
    @RequestMapping(value = "saveOrUpdateContact.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateContact (HttpServletRequest request, TmEmploy emp, HttpServletResponse response) {
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        
        String sysUser;
        sysUser = String.valueOf(request.getSession().getAttribute("sys.userName"));
        try {
            if (!"".equals(emp.getPkId())) {
                //update
                emp.setUpdateDate(new Date());
                emp.setUpdateUser(sysUser);
                this.cusContactsService.updateRecord(emp);
            } else {
                //add
                emp.setDelFlag("0");
                emp.setPkId(UUIDUtils.getUUID());
                emp.setUpdateDate(new Date());
                emp.setUpdateUser(sysUser);
                emp.setCreateDate(new Date());
                emp.setCreateUser(sysUser);
                this.cusContactsService.insertRecord(emp);
            }
            //成功
            map.put("msg", true);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return map;
    }
}
